Skip to content

Swift 6: complete concurrency checking for StreamChatUI #3660

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 32 commits into
base: swift-6
Choose a base branch
from

Conversation

laevandus
Copy link
Contributor

@laevandus laevandus commented May 5, 2025

Important

Merges to the main swift-6 branch, not develop

🔗 Issue Links

Resolves IOS-735

🎯 Goal

  • Set Swift version to 6 and implement complete concurrency checking in StreamChatUI

📝 Summary

  • Completion blocks need to be @Sendable in most of the cases
  • Controller completions and delegates must ensure main thread (through custom StreamConcurrency.onMain)
  • Controller delegates get nonisolated because any thread thread could call it and often MainActor guarded type implements these delegates (e.g. UIViewController subclass)
  • Tests use nonisolated(unsafe) a lot because otherwise most of the test must be rewritten (huge effort)
  • Sendable conformance to many types
  • Many protocols and types related to UI get @MainActor requirement
  • Upgrade Nuke to version 12.8 (otherwise we can't compile with complete concurrency checking)
  • Patch SwiftyGif for supporting complete concurrency checking

🛠 Implementation

LLC controllers support any queue for delegate callbacks and completion handlers. Therefore we need to ensure that these run on the main thread when updating UI code. This is where the custom MainActor.ensureIsolated(_) comes into the play. It just ensures that code triggered from these code paths are always on the main thread.

Public API which requires MainActor are annotated with @preconcurrency @MainActor which is the backwards compatibility support. In the next major version we would clean it up.

🧪 Manual Testing Notes

Manual testing in #3661

☑️ Contributor Checklist

  • I have signed the Stream CLA (required)
  • This change should be manually QAed
  • Changelog is updated with client-facing changes
  • Changelog is updated with new localization keys
  • New code is covered by unit tests
  • Documentation has been updated in the docs-content repo

# Conflicts:
#	Tests/StreamChatUITests/SnapshotTests/ChatChannelList/Search/ChatMessageSearchVC_Tests.swift
#	Tests/StreamChatUITests/SnapshotTests/ChatMessageList/ChatMessage/ChatMessageMarkdown_Tests.swift
@laevandus laevandus added 🎨 SDK: StreamChatUI Tasks related to the StreamChatUI SDK ⏫ Dependencies Update A PR that updates SDK Dependencies ✅ Feature An issue or PR related to a feature labels May 5, 2025
@laevandus laevandus requested a review from a team as a code owner May 5, 2025 07:39
@laevandus laevandus marked this pull request as draft May 5, 2025 07:39
Copy link

github-actions bot commented May 5, 2025

1 Warning
⚠️ Big PR
1 Message
📖 There seems to be app changes but CHANGELOG wasn't modified.
Please include an entry if the PR includes user-facing changes.
You can find it at CHANGELOG.md.

Generated by 🚫 Danger

@Stream-SDK-Bot
Copy link
Collaborator

SDK Size

title develop branch diff status
StreamChat 7.2 MB 7.28 MB +81 KB 🟢
StreamChatUI 4.72 MB 4.77 MB +55 KB 🟢

@Stream-SDK-Bot
Copy link
Collaborator

SDK Performance

target metric benchmark branch performance status
MessageList Hitches total duration 10 ms 10.01 ms -0.1% 🔽 🟡
Duration 2.6 s 2.54 s 2.31% 🔼 🟢
Hitch time ratio 4 ms per s 3.94 ms per s 1.5% 🔼 🟢
Frame rate 75 fps 78.37 fps 4.49% 🔼 🟢
Number of hitches 1 1.2 -20.0% 🔽 🔴

Comment on lines 42 to 48
static var `default`: Appearance = .init()
static var `default`: Appearance {
get { queue.sync { _default } }
set { queue.sync { _default = newValue } }
}

private static let queue = DispatchQueue(label: "io.getstream.appearance", target: .global())
nonisolated(unsafe) private static var _default: Appearance = .init()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On the second look it actually does not feel like a good idea. Since this is used for UI code then it sounds like making the static property MainActor makes more sense here. Otherwise we do unnecessary context switches. Making it main actor will have consequences:

  • app level setup code must be done on the main thread
  • other code interacting with default must require main thread

Copy link
Contributor Author

@laevandus laevandus May 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general, options are:
a) opt-out with nonisolated(unsafe) which kind of loses the point of strict concurrency checking. SDK users can trigger crashes.
b) Internally uses main thread when accessing the default (which should be the 99% of cases when calling it)

    static var `default`: Appearance {
        get {
            MainActor.ensureIsolated { _default }
        }
        set {
            MainActor.ensureIsolated { _default = newValue }
        }
    }

and making Appearance @unchecked Sendable (lot of work to make it fully Sendable since this type captures so many other types, e.g formatters)
c) Make the default @MainActor and add MainActor requirement to all the other callsites
e) Use queue/lock for accessing the default state although it should (almost) always be main thread

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a) loses the point of concurrency checking
b) makes it easier to use default from places without main actor annotation (easier adoption), on the other hand, it does not look the nicest, but at least does not cause performance issues due to context switches
c) cleanest but harder to use for users since it forces MainActor
e) performance wise not good because this is used by UI code and should be almost always run on the main thread (that said, SDK users could have setup running on a background thread)

) {
self.listView = listView
self.impactFeedbackGenerator = impactFeedbackGenerator
self.impactFeedbackGenerator = impactFeedbackGenerator ?? UIImpactFeedbackGenerator(style: .medium)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Xcode 15 had compiler crashes and this was the only way I could get it compiling

@Stream-SDK-Bot
Copy link
Collaborator

Stream-SDK-Bot commented May 5, 2025

SDK Size

title develop branch diff status
StreamChat 7.2 MB 7.28 MB +81 KB 🟢
StreamChatUI 4.72 MB 4.8 MB +87 KB 🟢

Comment on lines 42 to 53
static var `default`: Appearance = .init()
static var `default`: Appearance {
get {
MainActor.ensureIsolated { _default }
}
set {
MainActor.ensureIsolated { _default = newValue }
}
}

// Shared instance is mutated only on the main thread without explicit
// main actor annotation for easier SDK setup.
nonisolated(unsafe) private static var _default: Appearance = .init()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At first I was thinking about making it @MainActor, but this is used in multiple init methods meaning all of these must be @MainActor as well. Moreover, it might make the SDK initialization more complex as well since SDK users need to make sure Appearance is changed only from the MainActor.
a) we just make default nonisolated(unsafe)
b) we do what we have above which internally forcing main actor (for making sure SDK users do not corrupt the default by changing it from background threads)

@laevandus laevandus marked this pull request as ready for review May 23, 2025 11:44
@Stream-SDK-Bot
Copy link
Collaborator

SDK Performance

target metric benchmark branch performance status
MessageList Hitches total duration 10 ms 5.01 ms 49.9% 🔼 🟢
Duration 2.6 s 2.55 s 1.92% 🔼 🟢
Hitch time ratio 4 ms per s 1.97 ms per s 50.75% 🔼 🟢
Frame rate 75 fps 77.93 fps 3.91% 🔼 🟢
Number of hitches 1 0.6 40.0% 🔼 🟢

Copy link

coderabbitai bot commented May 29, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⏫ Dependencies Update A PR that updates SDK Dependencies ✅ Feature An issue or PR related to a feature 🎨 SDK: StreamChatUI Tasks related to the StreamChatUI SDK
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants